package org.jeecg.modules.demo.yanhao.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.parser.Parser;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.RestUtil;
import org.jeecg.modules.demo.yanhao.entity.CookieInfo;
import org.jeecg.modules.demo.yanhao.service.ICookieInfoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.yanhao.entity.Evaluate;
import org.jeecg.modules.demo.yanhao.entity.YhBasic;
import org.jeecg.modules.demo.yanhao.vo.YhBasicPage;
import org.jeecg.modules.demo.yanhao.service.IYhBasicService;
import org.jeecg.modules.demo.yanhao.service.IEvaluateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 验号基本信息
 * @Author: jeecg-boot
 * @Date: 2020-09-17
 * @Version: V1.0
 */
@Api(tags = "验号基本信息")
@RestController
@RequestMapping("/yanhao/yhBasic")
@Slf4j
public class YhBasicController {
    @Autowired
    private IYhBasicService yhBasicService;
    @Autowired
    private IEvaluateService evaluateService;
    @Autowired
    private ICookieInfoService cookieInfoService;

    /**
     * 分页列表查询
     *
     * @param yhBasic
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "验号基本信息-分页列表查询")
    @ApiOperation(value = "验号基本信息-分页列表查询", notes = "验号基本信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(YhBasic yhBasic,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String username = sysUser.getUsername();
        QueryWrapper<YhBasic> queryWrapper = QueryGenerator.initQueryWrapper(yhBasic, req.getParameterMap());
        queryWrapper.eq("create_by", username);
        Page<YhBasic> page = new Page<YhBasic>(pageNo, pageSize);
        IPage<YhBasic> pageList = yhBasicService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param yhBasicPage
     * @return
     */
    @AutoLog(value = "验号基本信息-添加")
    @ApiOperation(value = "验号基本信息-添加", notes = "验号基本信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody YhBasicPage yhBasicPage) {
        YhBasic yhBasic = new YhBasic();
        BeanUtils.copyProperties(yhBasicPage, yhBasic);
        yhBasicService.saveMain(yhBasic, yhBasicPage.getEvaluateList());
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param yhBasicPage
     * @return
     */
    @AutoLog(value = "验号基本信息-编辑")
    @ApiOperation(value = "验号基本信息-编辑", notes = "验号基本信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody YhBasicPage yhBasicPage) {
        YhBasic yhBasic = new YhBasic();
        BeanUtils.copyProperties(yhBasicPage, yhBasic);
        YhBasic yhBasicEntity = yhBasicService.getById(yhBasic.getId());
        if (yhBasicEntity == null) {
            return Result.error("未找到对应数据");
        }
        yhBasicService.updateMain(yhBasic, yhBasicPage.getEvaluateList());
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "验号基本信息-通过id删除")
    @ApiOperation(value = "验号基本信息-通过id删除", notes = "验号基本信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        yhBasicService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "验号基本信息-批量删除")
    @ApiOperation(value = "验号基本信息-批量删除", notes = "验号基本信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.yhBasicService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "验号基本信息-通过id查询")
    @ApiOperation(value = "验号基本信息-通过id查询", notes = "验号基本信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        YhBasic yhBasic = yhBasicService.getById(id);
        if (yhBasic == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(yhBasic);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "评价-通过主表ID查询")
    @ApiOperation(value = "评价-通过主表ID查询", notes = "评价-通过主表ID查询")
    @GetMapping(value = "/queryEvaluateByMainId")
    public Result<?> queryEvaluateListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<Evaluate> evaluateList = evaluateService.selectByMainId(id);
        IPage<Evaluate> page = new Page<>();
        page.setRecords(evaluateList);
        page.setTotal(evaluateList.size());
        return Result.ok(page);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param yhBasic
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, YhBasic yhBasic) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<YhBasic> queryWrapper = QueryGenerator.initQueryWrapper(yhBasic, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<YhBasic> queryList = yhBasicService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<YhBasic> yhBasicList = new ArrayList<YhBasic>();
        if (oConvertUtils.isEmpty(selections)) {
            yhBasicList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            yhBasicList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<YhBasicPage> pageList = new ArrayList<YhBasicPage>();
        for (YhBasic main : yhBasicList) {
            YhBasicPage vo = new YhBasicPage();
            BeanUtils.copyProperties(main, vo);
            List<Evaluate> evaluateList = evaluateService.selectByMainId(main.getId());
            vo.setEvaluateList(evaluateList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "验号基本信息列表");
        mv.addObject(NormalExcelConstants.CLASS, YhBasicPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("验号基本信息数据", "导出人:" + sysUser.getRealname(), "验号基本信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		//查询Cookie配置
		Map<String, Object> map = new HashMap<>();
		map.put("is_enable", "Y");
		List<CookieInfo> cookieInfos = cookieInfoService.listByMap(map);
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<YhBasicPage> list = ExcelImportUtil.importExcel(file.getInputStream(), YhBasicPage.class, params);
				int size = list.size();
				for (CookieInfo cookieInfo : cookieInfos) {
					List<String> wangwang = new ArrayList<>();
					List<YhBasicPage> YhBasicPages = new ArrayList<>(10);
					int i = 0;
					for (YhBasicPage page : list) {
						i++;
						YhBasic po = new YhBasic();
						page.setCookieInfoId(cookieInfo.getId());
						BeanUtils.copyProperties(page, po);
						YhBasicPages.add(page);
						yhBasicService.saveMain(po, page.getEvaluateList());
						if (i == 10) {
							break;
						}
					}
					list.removeAll(YhBasicPages);
					for (YhBasicPage yhBasicPage : YhBasicPages) {
						wangwang.add(yhBasicPage.getWangwang());
					}
					this.publishTXMWWRateInfo(wangwang, cookieInfo.getCookie());
				}
				return Result.ok("文件导入成功！数据行数:" + size);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

	private JSONObject publishTXMWWRateInfo(List<String> wangwang, String cookie) {
		try {
			String urlPath = "http://www.51yanhao.com/GongjuUI/publishTXMWWRateInfo";

			// 中转请求问号参数
			JSONObject variables = new JSONObject();
			variables.put("wangwang", String.join(",", wangwang));
			HttpHeaders headers = new HttpHeaders();
			headers.set("Cookie", cookie);
			// 发送请求
			String httpURL = URLDecoder.decode(urlPath, "UTF-8");
			ResponseEntity<JSONObject> result =
					RestUtil.request(httpURL, HttpMethod.POST, headers, variables, null, JSONObject.class);
			return result.getBody();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return new JSONObject();
	}

	@PostMapping("/getRateInfo")
	public Result<?> getRateInfo(@RequestBody YhBasicPage yhBasicPage) {
		//查询Cookie配置
		Map<String, Object> map = new HashMap<>();
		map.put("is_enable", "Y");
		List<CookieInfo> cookieInfos = cookieInfoService.listByMap(map);
		List<YhBasicPage> yhBasicPages = getAllTXMWWRateInfo(yhBasicPage, cookieInfos);

		for (YhBasicPage page : yhBasicPages) {
			String isAvailable = "0";
			YhBasic po = new YhBasic();
			BeanUtils.copyProperties(page, po);

			//有评价不可用
			if (!page.getEvaluateList().isEmpty()) {
				isAvailable = "1";
			}
			//降权处置不为0不可用
			if (!"0".equals(po.getMsg())) {
				isAvailable = "1";
			}

			//未实名不可用
			if ("2".equals(po.getRealNameStatus())) {
				isAvailable = "1";
			}
			//卖家账号不可用
			if ("1".equals(po.getSellerTotalNum())) {
				isAvailable = "1";
			}

			if ("~".equals(po.getWeekCreditAverage())) {
				isAvailable = "2";
			} else {
				if (!StringUtils.isEmpty(po.getWeekCreditAverage())) {
					if (Double.parseDouble(po.getWeekCreditAverage()) > 4) {
						isAvailable = "1";
					}
				}
			}
			//降权处置为null未确定
			if (StringUtils.isEmpty(po.getMsg())) {
				isAvailable = "2";
			}
			po.setIsAvailable(isAvailable);
			yhBasicService.updateMain(po, page.getEvaluateList());
		}
		return Result.ok();
	}

	/**
	 * 查询列表
	 * @param page
	 * @param cookieInfos
	 * @return
	 */
	private List<YhBasicPage> getAllTXMWWRateInfo(YhBasicPage page, List<CookieInfo> cookieInfos) {
		List<YhBasicPage> yhBasicPages = new ArrayList<>();
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		String username = sysUser.getUsername();
		Map<String, Object> resMap = new HashMap<>();
		resMap.put("create_by", username);
		List<YhBasic> yhBasics = yhBasicService.listByMap(resMap);
		try {
			String urlPath = "http://www.51yanhao.com/Gongjuui/getAllTXMWWRateInfo";
			JSONObject variables = new JSONObject();
			variables.put("startDate", page.getFinishtsStr_begin().getTime());
			variables.put("endDate", page.getFinishtsStr_end().getTime());
			variables.put("pn", 1);
			variables.put("ps", 50);
			for (CookieInfo cookieInfo : cookieInfos) {
				String cookie = cookieInfo.getCookie();
				HttpHeaders headers = new HttpHeaders();
				headers.set("Cookie", cookie);
				// 发送请求
				String httpURL = URLDecoder.decode(urlPath, "UTF-8");
				ResponseEntity<JSONObject> result =
						RestUtil.request(httpURL, HttpMethod.POST, headers, variables, null, JSONObject.class);

				JSONObject jsonObj = result.getBody();
				List<Map<String, Object>> maps = (List<Map<String, Object>>) jsonObj.get("res");
				for (Map<String, Object> map : maps) {
					for (YhBasic yhBasic : yhBasics) {
						if (yhBasic.getWangwang().equals(String.valueOf(map.get("wangwang")))) {
							YhBasicPage yhBasicPage = this.getTXMWWInfoById(cookie, String.valueOf(map.get("id")));
							yhBasicPage.setWangwang(String.valueOf(map.get("wangwang")));
							yhBasicPage.setId(yhBasic.getId());
							yhBasicPages.add(yhBasicPage);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return yhBasicPages;
	}

	/**
	 * 根据id查询详情
	 * @param cookie
	 * @param id
	 * @return
	 */
	private YhBasicPage getTXMWWInfoById(String cookie, String id) {
		String urlPath = "http://www.51yanhao.com/Gongjuui/getTXMWWInfoById";
		JSONObject variables = new JSONObject();
		variables.put("infoid", id);
		YhBasicPage yhBasicPage = new YhBasicPage();
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.set("Cookie", cookie);
			// 发送请求
			String httpURL = URLDecoder.decode(urlPath, "UTF-8");
			ResponseEntity<JSONObject> result =
					RestUtil.request(httpURL, HttpMethod.GET, headers, variables, null, JSONObject.class);

			JSONObject jsonObj = result.getBody();
			yhBasicPage = JSON.toJavaObject(jsonObj, YhBasicPage.class);
			this.getWwList(yhBasicPage, cookie);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return yhBasicPage;
	}

	/**
	 * 根据旺旺账号查询评价
	 * @param yhBasicPage
	 * @param cookie
	 */
	private void getWwList(YhBasicPage yhBasicPage, String cookie) {
		String urlPath = "http://www.51yanhao.com/NetflowMission/getWwList";
		JSONObject variables = new JSONObject();
		variables.put("wangwang", yhBasicPage.getWangwang());
		List<Map<String, Object>> maps = new ArrayList<>();
		List<Evaluate> evaluates = new ArrayList<>();
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.set("Cookie", cookie);
			// 发送请求
			String httpURL = URLDecoder.decode(urlPath, "UTF-8");
			ResponseEntity<JSONObject> result =
					RestUtil.request(httpURL, HttpMethod.GET, headers, variables, null, JSONObject.class);

			JSONObject jsonObj = result.getBody();
			maps = (List<Map<String, Object>>) jsonObj.get("data");
			for (Map<String, Object> map : maps) {
				JSONObject jsonObject = (JSONObject) JSONObject.toJSON(map);
				Evaluate evaluate = JSON.toJavaObject(jsonObject, Evaluate.class);
				evaluates.add(evaluate);
			}

			yhBasicPage.setMsg(String.valueOf(jsonObj.get("msg")));
			yhBasicPage.setEvaluateList(evaluates);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
